<template>
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button  type="primary" v-auth="'followup:follow_up:exportXls'"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  type="primary" v-auth="'followup:follow_up:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button v-auth="'followup:follow_up:deleteBatch'">批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <FollowUpModal @register="registerModal" @success="handleSuccess"></FollowUpModal>

    <!-- 文件详情模态框 -->
    <FileDetailModal
      v-model:visible="fileDetailModalVisible"
      :files="currentFiles"
      :disabled="false"
      :fileOrigin="fileDetailOrigin"
      @preview="handlePreviewFileFromDetail"
      @download="handleDownloadFileFromDetail"
      @delete="handleDeleteFileFromDetail"
      @update:visible="fileDetailModalVisible = $event"
    />
  </div>
</template>

<script lang="ts" name="followup-followUp" setup>
  import {ref, reactive, computed, unref} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import {useModal} from '/@/components/Modal';
  import FollowUpModal from './components/FollowUpModal.vue'
  import {columns, searchFormSchema, superQuerySchema} from './FollowUp.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl, getFollowPlanFiles, getFollowUpFiles, downloadFile, deleteFile, getFileAccessHttpUrl} from './FollowUp.api';
  import {downloadFile as commonDownloadFile} from '/@/utils/common/renderUtils'; // Rename to avoid conflict
  import { useUserStore } from '/@/store/modules/user';
  import { message, Modal } from 'ant-design-vue';
  import { h } from 'vue';
  import { Icon } from '/@/components/Icon';
  import FileDetailModal from './components/FileDetailModal.vue';

  const queryParam = reactive<any>({});
  const userStore = useUserStore();
  const checkedKeys = ref<Array<string | number>>([]);
  //注册modal
  const [registerModal, {openModal}] = useModal();

  // 文件详情弹窗相关
  const fileDetailModalVisible = ref(false);
  const currentFiles = ref<any[]>([]);
  const fileDetailOrigin = ref<'followPlan' | 'followUpContent' | null>(null);
  const currentRecordId = ref(''); // 用于存储当前行的ID，以便刷新文件列表
   //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '客户跟进表',
           api: list,
           columns,
           canResize:false,
           formConfig: {
                //labelWidth: 120,
                schemas: searchFormSchema,
                autoSubmitOnEnter:true,
                showAdvancedButton:true,
                fieldMapToNumber: [
                ],
                fieldMapToTime: [
                ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
           },
           beforeFetch: (params) => {
             return Object.assign(params, queryParam);
           },
        },
        exportConfig: {
            name:"客户跟进表",
            url: getExportUrl,
            params: queryParam,
        },
        importConfig: {
            url: getImportUrl,
            success: handleSuccess
        },
    })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }

  /**
   * 显示文件详情模态框
   */
  async function showFileDetailModal(record: Recordable) {
    currentRecordId.value = record.id; // 保存当前行的ID

    // 获取跟进计划文件
    const planFiles = await getFollowPlanFiles(record.id);
    // 获取跟进记录文件
    const contentFiles = await getFollowUpFiles(record.id);

    // 合并文件列表，并添加来源标识
    const allFiles = [
      ...planFiles.map(file => ({ ...file, origin: 'followPlan' })),
      ...contentFiles.map(file => ({ ...file, origin: 'followUpContent' }))
    ];

    if (allFiles.length === 0) {
      message.info('当前记录没有关联文件。');
      return;
    }

    currentFiles.value = allFiles;
    fileDetailOrigin.value = null; // 在列表页显示时，不区分来源
    fileDetailModalVisible.value = true;
  }

  /**
   * 处理文件预览（从文件详情弹窗触发）
   */
  function handlePreviewFileFromDetail(file: any) {
    if (!file.id) {
      message.warning('未找到文件ID');
      return;
    }
    const url = getFileAccessHttpUrl(file.id);
    window.open(url, '_blank');
    message.success('文件预览请求已发送');
  }

  /**
   * 处理文件下载（从文件详情弹窗触发）
   */
  async function handleDownloadFileFromDetail(file: any) {
    if (!file.id) {
      message.warning('未找到文件ID');
      return;
    }
    try {
      const response = await downloadFile(file.id);
      const blob = new Blob([response], { type: response.type });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', file.fileName || 'download');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      message.success('文件下载成功');
    } catch (error) {
      console.error('文件下载失败:', error);
      message.error('文件下载失败');
    }
  }

  /**
   * 处理文件删除（从文件详情弹窗触发）
   */
  async function handleDeleteFileFromDetail(file: any) {
    if (!file.id) {
      message.error('无法获取文件ID，删除失败');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此文件吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteFile(file.id);
          message.success('文件删除成功');
          // 刷新文件列表
          await showFileDetailModal({ id: currentRecordId.value });
        } catch (error) {
          console.error('文件删除失败:', error);
          message.error('文件删除失败');
        }
      },
    });
  }

   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
           auth: 'followup:follow_up:edit'
         }
       ]
   }


  /**
   * 下拉操作栏
   */
  function getDropDownAction(record){
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '文件详情',
        onClick: showFileDetailModal.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft'
        },
        auth: 'followup:follow_up:delete'
      }
    ]
  }


</script>

<style lang="less" scoped>
  :deep(.ant-picker),:deep(.ant-input-number){
    width: 100%;
  }
</style>
